<template>
  <view class="chat-container">
    <!-- 自定义导航栏 -->
    <view class="nav-bar">
      <view class="nav-left">
        <view class="icon history-icon" @click="toggleSidebar">历史对话</view>
      </view>
      <view class="nav-title">AI聊天</view>
      <view class="nav-right">
        <view class="icon" @click="newChat">新对话</view>
        <view class="icon">头像</view>
      </view>
    </view>

    <!-- 侧边栏 -->
    <view class="sidebar" :class="{ 'sidebar-show': showSidebar }">
      <view class="sidebar-header">历史对话记录</view>
      <scroll-view
        class="sidebar-content"
        scroll-y="true"
        :scroll-into-view="scrollToId"
      >
        <view
          v-for="(item, index) in historyList"
          :key="index"
          class="history-item"
        >
          <view
            class="history-title"
            @click="loadHistory(item.conversationId)"
            >{{ item.title }}</view
          >
          <view
            class="delete-btn"
            @click.stop="deleteHistory(index, item.conversationId)"
            >删除</view
          >
        </view>
      </scroll-view>
    </view>

    <!-- 遮罩层 -->
    <view class="sidebar-mask" v-if="showSidebar" @click="toggleSidebar"></view>

    <!-- 对话内容区 -->
    <scroll-view
      class="chat-content"
      scroll-y="true"
      @scrolltolower="loadMoreMessages"
      :scroll-into-view="lastMsgId"
    >
      <view
        v-for="(msg, index) in chatHistory"
        :key="index"
        class="message"
        :id="'msg-' + index"
      >
        <view v-if="msg.isUser" class="user-message">
          <view class="message-bubble">{{ msg.content }}</view>
        </view>
        <view v-else class="ai-message">
          <view class="message-bubble">
            {{ msg.content }}
            <!-- 流式传输中的光标效果 -->
            <view v-if="msg.isStreaming" class="typing-cursor"></view>
          </view>
          <!-- 流式传输中的加载动画 -->
          <view v-if="msg.isStreaming" class="stream-loading">
            <view class="dot"></view>
            <view class="dot"></view>
            <view class="dot"></view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 输入对话框 -->
    <view class="input-container">
      <input
        v-model="inputText"
        class="input"
        placeholder="请输入消息..."
        @confirm="sendMessage"
        :disabled="isLoading"
      />
      <button
        class="document-button"
        @click="chooseDocument"
        :disabled="isLoading"
      >
        文档
      </button>
      <button
        class="send-button"
        @click="sendMessage"
        :disabled="isLoading || !inputText.trim()"
      >
        <view v-if="isLoading" class="loading-spinner"></view>
        <text v-else>发送</text>
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, nextTick, computed, onUnmounted } from "vue";
import { useChatApi } from "../../api/chat";
import { useUserStore } from "../../stores/User";

const { conversation, createChat, deleteChat, getAllMessage, getChat } =
  useChatApi();
const { userId, token } = useUserStore();

// 定义响应式数据
const inputText = ref("");
const chatHistory = ref([]);
const showSidebar = ref(false);
const chatId = ref("");
const scrollToId = ref("");
const historyList = ref([]);
const socketTask = ref(null);
const isLoading = ref(false);
const lastMsgId = ref("");
const currentStreamingIndex = ref(-1); // 当前流式传输的消息索引

// 发送消息
const sendMessage = async () => {
  if (!inputText.value.trim() || isLoading.value) return;

  try {
    isLoading.value = true;

    if (chatId.value === "") {
      const res = await createChat({
        userId: userId,
        title: inputText.value,
      });

      historyList.value.push({
        conversationId: res.data.conversationId,
        title: res.data.title,
      });

      chatId.value = res.data.conversationId;
    }

    // 添加用户消息
    chatHistory.value.push({
      isUser: true,
      content: inputText.value,
    });

    // 添加AI消息占位符，用于流式传输
    const aiMessageIndex = chatHistory.value.length;
    chatHistory.value.push({
      isUser: false,
      content: "",
      isStreaming: true,
    });

    currentStreamingIndex.value = aiMessageIndex;

    // 清空输入框
    const userMessage = inputText.value;
    inputText.value = "";

    // 滚动到底部
    nextTick(() => {
      scrollToId.value = `msg-${aiMessageIndex}`;
    });

    // 使用流式传输调用API
    await streamResponse(chatId.value, userMessage, aiMessageIndex);
  } catch (error) {
    uni.showModal({
      title: "提示",
      content: error.message || "发送消息失败",
      showCancel: false,
      confirmText: "确定",
      confirmColor: "#a020f0",
    });

    // 移除流式传输占位消息
    if (currentStreamingIndex.value !== -1) {
      chatHistory.value.splice(currentStreamingIndex.value, 1);
      currentStreamingIndex.value = -1;
    }
  } finally {
    isLoading.value = false;
  }
};

// 流式传输API响应
const streamResponse = async (conversationId, userMessage, aiMessageIndex) => {
  try {
    // 在实际项目中，这里应该替换为真正的流式API调用
    // 以下是模拟流式传输的实现

    // 模拟的AI响应文本
    var res = await conversation(conversationId, userMessage);
    const lorem = res.message;
    // `您好！您刚才说："${userMessage}"。这是一个流式传输的演示。在UniApp中实现流式传输可以提升用户体验，让用户感受到实时的交互效果。流式传输通过逐步显示内容，而不是等待整个响应完成再显示，这样用户不需要等待太久就能看到部分结果。`;
    console.log(lorem);
    // 模拟流式传输
    let index = 0;
    const chunkSize = 3; // 每次显示的字符数
    const interval = setInterval(() => {
      if (index >= lorem.length) {
        clearInterval(interval);
        // 完成流式传输
        chatHistory.value[aiMessageIndex].isStreaming = false;
        currentStreamingIndex.value = -1;
        return;
      }

      const chunk = lorem.substring(index, index + chunkSize);
      index += chunkSize;

      // 更新消息内容
      chatHistory.value[aiMessageIndex].content += chunk;

      // 滚动到底部
      nextTick(() => {
        scrollToId.value = `msg-${aiMessageIndex}`;
        lastMsgId.value = "msg-" + (messages.value.length - 1);
      });
    }, 50);

    // 在实际项目中，应该使用以下方式：
    /*
			// 创建WebSocket连接
			socketTask.value = uni.connectSocket({
				url: `wss://your-api.com/stream?conversationId=${conversationId}`,
				success: () => console.log('Socket连接成功'),
			});
			
			// 发送消息
			socketTask.value.send({
				data: JSON.stringify({ message: userMessage }),
				success: () => console.log('消息发送成功'),
			});
			
			// 监听消息
			socketTask.value.onMessage((res) => {
				if (typeof res.data === 'string') {
					// 追加内容
					chatHistory.value[aiMessageIndex].content += res.data;
					
					// 滚动到底部
					nextTick(() => {
						scrollToId.value = `msg-${aiMessageIndex}`;
					});
				}
			});
			
			// 监听关闭
			socketTask.value.onClose(() => {
				chatHistory.value[aiMessageIndex].isStreaming = false;
				currentStreamingIndex.value = -1;
				socketTask.value = null;
			});
			*/
  } catch (error) {
    console.error("流式传输错误:", error);
    chatHistory.value[aiMessageIndex].content = "抱歉，获取回答时出错";
    chatHistory.value[aiMessageIndex].isStreaming = false;
    currentStreamingIndex.value = -1;
  }
};

// 新对话
const newChat = () => {
  // 关闭现有的WebSocket连接
  if (socketTask.value) {
    socketTask.value.close();
    socketTask.value = null;
  }

  // 清空聊天记录
  chatHistory.value = [];
  chatId.value = "";
  currentStreamingIndex.value = -1;
};

// 选择文档
const chooseDocument = async () => {
  uni.showModal({
    title: "提示",
    content: "文档功能将在后续版本中开放",
    showCancel: false,
    confirmText: "确定",
    confirmColor: "#a020f0",
  });
};

// 加载更多消息
const loadMoreMessages = () => {
  console.log("加载更多消息");
};

// 切换侧边栏显示/隐藏
const toggleSidebar = () => {
  showSidebar.value = !showSidebar.value;
};

// 删除历史记录
const deleteHistory = async (index, chatId) => {
  uni.showModal({
    title: "确认删除",
    content: "确定要删除这条历史记录吗？",
    success: async (res) => {
      if (res.confirm) {
        try {
          await deleteChat(chatId);
          historyList.value.splice(index, 1);
          chatHistory.value = [];
          uni.showToast({
            title: "删除成功",
            icon: "success",
          });
        } catch (error) {
          uni.showModal({
            title: "提示",
            content: error.message || "删除失败",
            showCancel: false,
            confirmText: "确定",
            confirmColor: "#a020f0",
          });
        }
      }
    },
  });
};

// 加载历史记录
const loadHistory = async (id) => {
  uni.showToast({
    title: "正在加载对话...",
    icon: "loading",
  });
  showSidebar.value = false;
  chatHistory.value = [];
  chatId.value = id;
  // 实际加载历史记录的代码
  try {
    var list = await getAllMessage(id);
    console.log(list.data);

    for (var res of list.data) {
      console.log(res);
      console.log({
        isUser: true,
        content: res.content,
      });
      if (res.role == "user") {
        chatHistory.value.push({
          isUser: true,
          content: res.content,
        });
      } else {
        chatHistory.value.push({
          isUser: false,
          content: res.content,
        });
      }
    }
  } catch (error) {
    uni.showModal({
      title: "提示",
      content: error.message || "加载消息记录失败",
      showCancel: false,
      confirmText: "确定",
      confirmColor: "#a020f0",
    });
  }
};

onMounted(async () => {
  if (!userId || !token) {
    uni.showModal({
      title: "提示",
      content: "用户未登录",
      showCancel: false,
      confirmText: "确定",
      confirmColor: "#a020f0",
    });

    uni.navigateTo({
      url: "/pages/login/login",
    });
  }
  try {
    const res = await getChat(userId);
    historyList.value = res.data || [];
  } catch (error) {
    uni.showModal({
      title: "提示",
      content: error.message || "加载会话记录失败",
      showCancel: false,
      confirmText: "确定",
      confirmColor: "#a020f0",
    });
  }
});

// 组件卸载时关闭WebSocket连接
onUnmounted(() => {
  if (socketTask.value) {
    socketTask.value.close();
    socketTask.value = null;
  }
});
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 95vh;
  background: linear-gradient(135deg, #6a5acd, #00bfff);
  position: relative;
}

.nav-bar {
  height: 120rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30rpx;
  background: linear-gradient(135deg, #6a5acd, #00bfff);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav-left,
.nav-right {
  gap: 15px;
  display: flex;
  align-items: center;
}

.nav-title {
  font-size: 40rpx;
  font-weight: 600;
  color: #fff;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.icon {
  color: #ffffff;
  padding: 8px 12px;
  border-radius: 4px;
  transition: background-color 0.3s, color 0.3s;
  cursor: pointer;
}

.icon:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.history-icon {
  margin-right: 10px;
  color: #fff;
}

.sidebar {
  margin-top: 2%;
  position: fixed;
  top: 120rpx;
  left: -600rpx;
  width: 560rpx;
  height: calc(100% - 120rpx);
  background-color: #fff;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
  z-index: 99;
  transition: all 0.3s ease;
}

.sidebar-show {
  left: 0;
}

.sidebar-header {
  padding: 20px;
  font-size: 18px;
  font-weight: bold;
  border-bottom: 1px solid #eee;
  background: linear-gradient(135deg, #6a5acc, #00bfff);
  color: #fff;
}

.sidebar-content {
  height: calc(100% - 60px);
  padding: 10px;
}

.history-item {
  width: 80%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  margin-bottom: 8px;
  border-radius: 6px;
  background-color: #f5f5f5;
  cursor: pointer;
}

.history-title {
  flex: 1;
}

.history-item:hover {
  background-color: #e0f7fa;
}

.delete-btn {
  padding: 4px 8px;
  background-color: #ff4d4f;
  color: white;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
}

.delete-btn:hover {
  background-color: #ff7875;
}

.sidebar-mask {
  position: fixed;
  top: 60px;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 98;
}

.chat-content {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
  background-color: #fff;
  padding-top: 5px;
  height: calc(100vh - 240rpx);
  box-sizing: border-box;
}

.message {
  margin-bottom: 15px;
}

.user-message {
  display: flex;
  justify-content: flex-end;
  padding-right: 25px;
}

.ai-message {
  display: flex;
  justify-content: flex-start;
  padding-left: 25px;
  flex-direction: column;
}

.message-bubble {
  max-width: 80%;
  padding: 10px;
  border-radius: 15px;
  background-color: #e0f7fa;
  color: #00796b;
  position: relative;
}

/* 流式传输样式 */
.typing-cursor {
  display: inline-block;
  width: 8px;
  height: 18px;
  background: #00796b;
  margin-left: 2px;
  vertical-align: middle;
  animation: blink 1s infinite;
}

@keyframes blink {
  0%,
  100% {
    opacity: 1;
  }

  50% {
    opacity: 0;
  }
}

.stream-loading {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 8px;
}

.stream-loading .dot {
  width: 8px;
  height: 8px;
  background-color: #00796b;
  border-radius: 50%;
  margin: 0 4px;
  animation: pulse 1.5s infinite ease-in-out;
}

.stream-loading .dot:nth-child(1) {
  animation-delay: -0.32s;
}

.stream-loading .dot:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes pulse {
  0%,
  80%,
  100% {
    transform: scale(0.5);
  }

  40% {
    transform: scale(1);
  }
}

.loading-spinner {
  width: 20px;
  height: 20px;
  border: 3px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: white;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.input-container {
  height: 120rpx;
  padding: 30rpx;
  display: flex;
  background: linear-gradient(135deg, #6a5acd, #00bfff);
  align-items: center;
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
}

.input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 15px;
  margin-right: 15px;
  height: 80rpx;
  background-color: #fff;
}

.send-button,
.document-button {
  padding: 0 25px;
  background-color: #4caf50;
  color: #fff;
  border: none;
  border-radius: 15px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 10px;
  transition: background-color 0.3s;
}

.send-button:disabled,
.document-button:disabled {
  background-color: #a5d6a7;
  cursor: not-allowed;
}

.send-button:hover:not(:disabled),
.document-button:hover:not(:disabled) {
  background-color: #388e3c;
}

.document-button {
  background-color: #00796b;
}

.document-button:hover:not(:disabled) {
  background-color: #004d40;
}
</style>
